package co.legu.carpool.api.route.controller;

import co.legu.carpool.api.route.entity.Route;
import co.legu.carpool.api.route.service.IRouteService;
import co.legu.carpool.common.bean.IdVO;
import co.legu.carpool.util.QrCodeUtils;
import co.legu.modules.auth.annotation.NoNeedAuth;
import co.legu.modules.common.bean.Result;
import co.legu.modules.common.util.Streams;
import co.legu.modules.common.util.Strings;
import co.legu.modules.pager.annotation.Pager;
import co.legu.modules.qrcode.QRCode;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.MessageFormat;
import java.util.Base64;

/**
 * <p>
 * 路线 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/api/route")
public class RouteController {
    @Autowired
    private IRouteService routeService;
    @Value("${wechat.appId}")
    private String appid;

    /**
     * @api {post} /api/route/addOrUpdate 路线 - 添加或修改路线
     * @apiDescription 添加或修改路线
     * @apiGroup route
     * @apiVersion 1.0.0
     * @apiParam {String} id 修改时使用
     * @apiParam {String} startPoint 起点*
     * @apiParam {String} endPoint 终点*
     * @apiSuccess {data} object 通用返回值
     */
    @PostMapping("/addOrUpdate")
    public Result<?> addOrUpdate(@RequestBody @Valid Route add) {
        add.setDeleted(false);

        if (Strings.isBlank(add.getId())){
            // 添加前的校验
            var routeCount = routeService.lambdaQuery().eq(Route::getStartPoint, add.getStartPoint()).eq(Route::getEndPoint, add.getEndPoint()).count();
            var routeCount2 = routeService.lambdaQuery().eq(Route::getStartPoint, add.getEndPoint()).eq(Route::getEndPoint, add.getStartPoint()).count();
            if (routeCount > 0 || routeCount2 > 0 ){
                return Result.fail("当前路线已经拥有。");
            }

            // 默认值添加
            add.setId(IdWorker.getIdStr());
            // 添加数据
            boolean addResult = routeService.save(add);
            return Result.auto(addResult);
        }else {
            // 修改前的校验
            var routeCount = routeService.lambdaQuery().eq(Route::getStartPoint, add.getStartPoint()).eq(Route::getEndPoint, add.getEndPoint()).ne(Route::getId,add.getId()).count();
            var routeCount2 = routeService.lambdaQuery().eq(Route::getStartPoint, add.getEndPoint()).eq(Route::getEndPoint, add.getStartPoint()).ne(Route::getId,add.getId()).count();
            if (routeCount > 0 || routeCount2 > 0 ){
                return Result.fail("当前路线已经拥有。");
            }

            // 修改数据
            boolean updResult = routeService.updateById(add);
            return Result.auto(updResult);
        }

    }

    /**
     * @api {post} /api/route/delete 路线 - 删除路线
     * @apiDescription 删除路线
     * @apiGroup route
     * @apiVersion 1.0.0
     * @apiParam {String} id 路线ID*
     * @apiSuccess {data} object 通用返回值
     */
    @PostMapping("/delete")
    public Result<?> delete(@RequestBody @Valid IdVO idVO) {
        boolean delResult = routeService.removeById(idVO.getId());
        return Result.auto(delResult);
    }

    /**
     * @api {get} /api/route/info 路线 - 查询路线
     * @apiDescription 查询路线
     * @apiGroup route
     * @apiVersion 1.0.0
     * @apiParam {String} id 路线ID
     * @apiSuccess {String} id 路线ID*
     * @apiSuccess {String} startPoint 起点*
     * @apiSuccess {String} endPoint 终点*
     */
    @GetMapping("/info")
    public Result<?> info(String id) {
        //查询
        var info = routeService.getById(id);
        return Result.success(info);
    }

    /**
     * 分页查询
     *
     * @return 分页后的实体
     */
    @Pager
    @GetMapping("/list")
    public Result<?> list() {
        //查询数据
        var list = routeService.lambdaQuery().list();
        return Result.success(list);
    }

    /**
     * 获取路线二维码
     * @param id
     * @return
     */
    /**
     * @api {get} /api/route/QRCode
     * @apiDescription 获取路线二维码
     * @apiGroup route
     * @apiVersion 1.0.0
     * @apiSuccess {String} date BASE64的图片
     */
    @NoNeedAuth
    @GetMapping("/QRCode")
    public Result<?> QRCode(String id) throws Exception{
        var route = routeService.getById(id);
        if (route == null) return Result.fail("没有当前路线");

        String url = MessageFormat.format(
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}" +
                        "&redirect_uri=https://carpool.shanch.cn/api/wechat/{1}/login?routeId={2}" +
                        "&response_type=code&scope=snsapi_base&state=btn1#wechat_redirect",
                appid,appid,route.getId()
        );
        // 背景图片
        var bgImg = ImageIO.read(new ClassPathResource("/static/background.jpg").getInputStream());

        // 二维码图片
        var qrCodeImage = QRCode.content(url).toImg();

        // 写入背景和文字
        QrCodeUtils.writeBgImgAndText(bgImg,qrCodeImage,route.getStartPoint()+"——"+route.getEndPoint(),
                200,400,2080,2080,bgImg.getHeight()-400,
                100, Color.black);
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ImageIO.write(bgImg, "PNG", out);
            var in = new ByteArrayInputStream(out.toByteArray());
            Streams.copy(in, out);
            byte[] buf = out.toByteArray();
            var str = Base64.getEncoder().encodeToString(buf);
            return Result.success(str);
        }
    }

}

